/**
*  
* @Function 批量核查Controller
* @ProjectName credit-data-platform 
* @PackageName com.py.credit.controller    
* @FileName BatchReportController.java    
* @Date 2018年10月18日下午3:58:32
* @Author Min DongXv
* @Copyright (c) 2018, 金电联行 All Rights Reserved.   
*   
*/
package com.py.credit.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.MessageConstants;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.BatchReportFieldsEnum;
import com.py.credit.service.BatchReportService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.credit.utils.UniqueIdUtils;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * 
 * @Function 批量核查Controller
 * @ClassName BatchReportController
 * @Date 2018年10月18日 下午3:58:32
 * @Author Min DongXv
 * 
 */
@RestController
@RequestMapping(value = "/batchReport")
public class BatchReportController extends BaseController {

	// 用户自定义列缓存key
	private static final String USER_DEFINED_COLUMN_KEY = "batchReport";

	private static final String MANAGER_ID = "managerId";

	@Autowired
	private RemoteBaseService remoteBaseService;

	@Autowired
	private BatchReportService batchReportService;

	@Value("${absolutepath}")
	private String absolutepath;

	@Value("${pdfJsPath}")
	private String pdfJsPath;

	@Value("${googlePath}")
	private String googlePath;

	@Value("${pdfPagePath}")
	private String pdfPagePath;

	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		return new RestServiceResult<>(BatchReportFieldsEnum.getOptionalColumns());
	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		return new RestServiceResult<>(BatchReportFieldsEnum.getAdvancedConditionColumns());
	}

	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg(MessageConstants.SYSTEM_ERROR);
				ExceptionLogger.error("BatchReportController#addShowColunms", MessageConstants.NOT_FIND_CURRENT_USER);
				return result;
			}
			MapCache.set(userInfo.getId() + "_" + USER_DEFINED_COLUMN_KEY, columns);
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return result;
	}

	/**
	 * 
	 * @api {get} /batchReport/batchList.json 分页查询批量核查列表
	 * @apiName batchReportList
	 * @apiVersion 0.0.1
	 * @apiGroup 批量核查
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/batchList.json")
	public RestServiceResult<List<Map<String, Object>>> batchList(Page page, HttpServletRequest request,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<>();
		// 获取当前用户信息
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg(MessageConstants.SYSTEM_ERROR);
				ExceptionLogger.error("BatchReportController#batchReportList", MessageConstants.NOT_FIND_CURRENT_USER);
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		Long userId = userInfo.getId();
		Long deptId = userInfo.getOfficeId();
		String rolename = userInfo.getRoleName();
		String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + USER_DEFINED_COLUMN_KEY);
		List<String> showColumns = (configColumns == null || configColumns.length == 0)
				? BatchReportFieldsEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
		List<Map<String, Object>> data = new ArrayList<Map<String,Object>>();
				try {
			
			if(rolename.equals("系统管理员")) {
				data = batchReportService.getBatchReport(showColumns,
						new String[] { "deptId", MANAGER_ID }, condition, page,null,null);
			}else if(rolename.equals("部门管理员")) {
				data = batchReportService.getBatchReport(showColumns,
						new String[] { "deptId", MANAGER_ID }, condition, page,deptId,null);
			}else {
				data = batchReportService.getBatchReport(showColumns,
						new String[] { "deptId", MANAGER_ID }, condition, page,deptId,userId);
			}
//			data = batchReportService.getBatchReport(showColumns,
//					new String[] { "deptId", MANAGER_ID }, condition, page);
			if (!CollectionUtils.isEmpty(data)) {
				Set<Integer> userIds = new HashSet<>(data.size());
				for (Map<String, Object> m : data) {
					if (null != m && m.containsKey(MANAGER_ID) && null != m.get(MANAGER_ID)) {
						userIds.add(Integer.parseInt(String.valueOf(m.get(MANAGER_ID))));
					}
				}
				remoteBaseService.matchUserDeptName(data, result, token, userIds, MANAGER_ID, "managerName",
						"deptName");
			}
			result.setData(data);
			result.setCount(page.getTotalCount());
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("列表数据查询异常，请稍后再试");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchReport/upload.do 批量核查上传
	 * @apiName uploadBatchReport
	 * @apiVersion 0.0.1
	 * @apiGroup 批量核查
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/upload.do")
	public RestServiceResult<Object> uploadBatchReport(@RequestParam(value = "file") CommonsMultipartFile file,
			HttpServletRequest request, HttpServletResponse response) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg(MessageConstants.SYSTEM_ERROR);
				ExceptionLogger.error("BatchReportController#uploadBatchReport",
						MessageConstants.NOT_FIND_CURRENT_USER);
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		// 生成批次ID
		String batchId = UniqueIdUtils.createFileName("BR", null);
		// 上传操作
		try {
			result = batchReportService.uploadBatchReport(file, userInfo, absolutepath, batchId);
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("文件上传异常！");
			return result;
		}
		// 上传成功直接进行解析
		if (RestServiceResult.CODE_SUCCESS == result.getCode()) {
			try {
				return batchReportService.dealFile(String.valueOf(result.getData()), batchId);
			} catch (Exception e) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("文件解析异常！");
				return result;
			}
		} else {
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchReport/templateDownload.json 批量核查模板下载
	 * @apiName templateDownload
	 * @apiVersion 0.0.1
	 * @apiGroup 批量核查
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/templateDownload.json")
	public RestServiceResult<Object> templateDownload(HttpServletResponse response) {
		try {
			return batchReportService.templateDownload(response);
		} catch (Exception e) {
			ExceptionLogger.error("BatchReportController#templateDownload", "模板下载异常！ERROR：" + e.getMessage(), e);
			RestServiceResult<Object> result = new RestServiceResult<>();
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("模板下载异常，请稍后再试");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchReport/reportTask.do 批量核查定时任务
	 * @apiName reportTask
	 * @apiVersion 0.0.1
	 * @apiGroup 批量核查
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping("/reportTask.do")
	public RestServiceResult<Object> reportTask() {
		try {
			return batchReportService.createReport(absolutepath, pdfJsPath, googlePath, pdfPagePath);
		} catch (Exception e) {
			RestServiceResult<Object> result = new RestServiceResult<>();
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("报告生成异常");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchReport/export.json 批量核查导出
	 * @apiName exportData
	 * @apiVersion 0.0.1
	 * @apiGroup 批量核查
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/export.json")
	public RestServiceResult<List<Map<String, Object>>> exportData(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition,
			@RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
			HttpServletResponse response, HttpServletRequest request) {
		page.setLimit(1000);
		List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
		List<OptionalColumn> optionalColumns = BatchReportFieldsEnum.getOptionalColumns();
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<>();
		// 获取当前用户信息
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg(MessageConstants.SYSTEM_ERROR);
				ExceptionLogger.error("BatchReportController#exportData", MessageConstants.NOT_FIND_CURRENT_USER);
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		Long userId = userInfo.getId();
		Long deptId = userInfo.getOfficeId();
		String rolename = userInfo.getRoleName();
		List<Map<String, Object>> data = new ArrayList<Map<String,Object>>();
		try {
			if(rolename.equals("系统管理员")) {
				data = batchReportService.getBatchReport(showColumns,
						new String[] { "deptId", MANAGER_ID }, condition, page,null,null);
			}else if(rolename.equals("部门管理员")) {
				data = batchReportService.getBatchReport(showColumns,
						new String[] { "deptId", MANAGER_ID }, condition, page,deptId,null);
			}else {
				data = batchReportService.getBatchReport(showColumns,
						new String[] { "deptId", MANAGER_ID }, condition, page,deptId,userId);
			}
			
			if (!CollectionUtils.isEmpty(data)) {
				Set<Integer> userIds = new HashSet<>(data.size());
				for (Map<String, Object> m : data) {
					if (null != m && m.containsKey(MANAGER_ID) && null != m.get(MANAGER_ID)) {
						userIds.add(Integer.parseInt(String.valueOf(m.get(MANAGER_ID))));
					}
				}
				remoteBaseService.matchUserDeptName(data, result, token, userIds, MANAGER_ID, "managerName",
						"deptName");
			}
			ExcelUtil.downloadExcel(response, data, "批量核查", "批量核查", showColumns, optionalColumns);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("批量核查导出异常，请稍后再试");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchReport/zipDownload.json 批量核查打包下载
	 * @apiName zipDownload
	 * @apiVersion 0.0.1
	 * @apiGroup 批量核查
	 * @apiParam {String} batchId 批次ID
	 * @apiParamExample {json} 请求参数示例 {"filePath":"/a.pdf"}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping("/zipDownload.json")
	public RestServiceResult<Object> zipDownload(HttpServletResponse response,
			@RequestParam(value = "filePath", defaultValue = "", required = true) String filePath,
			@RequestParam(value = "batchId", defaultValue = "", required = true) String batchId) {
		try {
			return batchReportService.zipDownload(batchId, filePath, response, "批量核查");
		} catch (Exception e) {
			ExceptionLogger.error("BatchReportController#zipDownload", "压缩包下载异常！ERROR：" + e.getMessage(), e);
			RestServiceResult<Object> result = new RestServiceResult<>();
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("下载异常，请稍后再试");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchReport/zipCanDownload.json 压缩包是否可以下载
	 * @apiName zipCanDownload
	 * @apiVersion 0.0.1
	 * @apiGroup
	 * @apiParam {String} batchId 批次信息
	 * @apiParamExample {json} 请求参数示例 {"batchId":"1"}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping("/zipCanDownload.json")
	public RestServiceResult<String> zipCanDownload(HttpServletResponse response,
			@RequestParam(value = "batchId", defaultValue = "", required = true) String batchId) {
		try {
			return batchReportService.zipCanDownload(absolutepath, batchId, "批量核查.zip");
		} catch (Exception e) {
			ExceptionLogger.error("BatchReportController#zipCanDownload", "压缩包是否可以下载异常！ERROR：" + e.getMessage(), e);
			RestServiceResult<String> result = new RestServiceResult<>();
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("下载异常，请稍后再试");
			return result;
		}
	}
}